import React, { useEffect } from "react";
import { Card, Form, Input, Button, message } from "antd";
import { useNavigate, useParams } from "react-router-dom";
import {
  addHospital,
  getUpdateHospital,
  updateHospital,
} from "@/api/hospital/setHospital";

export default function AddHospital() {
  const navigate = useNavigate();

  const [form] = Form.useForm();

  const params = useParams();
  const { id } = params;

  const goSetHospital = () => {
    navigate(-1);
  };

  const onFinish = async (values: any) => {
    if (id) {
      await updateHospital({
        ...values,
        id,
      });
      message.success("修改成功");
    } else {
      await addHospital(values);
      message.success("添加成功");
    }
    navigate(-1);
  };

  const getUpdateHospitalFun = async () => {
    const res = await getUpdateHospital(id as string);
    form.setFieldsValue(res);
  };

  useEffect(() => {
    getUpdateHospitalFun();
  }, []);

  return (
    <div>
      <Card>
        <Form
          form={form}
          labelCol={{ span: 3 }}
          wrapperCol={{ span: 21 }}
          onFinish={onFinish}
        >
          <Form.Item
            label="医院名称"
            name="hosname"
            rules={[{ required: true, message: "请输入医院名称" }]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            label="医院编号"
            name="hoscode"
            rules={[{ required: true, message: "请输入医院编号" }]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            label="api路径"
            name="apiUrl"
            rules={[{ required: true, message: "请输入api路径" }]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            label="联系人姓名"
            name="contactsName"
            rules={[{ required: true, message: "请输入联系人姓名" }]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            label="联系人手机"
            name="contactsPhone"
            rules={[
              {
                required: true,
                message: "请输入联系人手机",
                pattern: /^1[3-9]\d{9}$/,
              },
            ]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item colon={false} label>
            <Button
              type="primary"
              style={{ marginRight: 20 }}
              htmlType="submit"
            >
              保存
            </Button>
            <Button onClick={goSetHospital}>返回</Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}
